<?php

namespace App\Jobs\CallingCards;

use App\Models\FeishuCallingCard\FeishuCallingCardUsersStoriesLog;
use App\Service\CallingCards\UsersStoriesLogService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class AutoCloseUsersStoriesLog implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    const QUEUE_NAME = '{tiger-AutoCloseUsersStoriesLog}';

    public $tries = 9; //尝试 9 次

    public $timeout = 1800;// 超时时间

    private int    $storiesId;
    private string $userId;
    private int    $source;

    /**
     * 自动关闭加盟商名片微信小程序用户查看文章记录表
     *
     * @param int $storiesId
     * @param string $userId
     * @param int $source
     */
    public function __construct(int $storiesId, string $userId, int $source)
    {
        $this->storiesId = $storiesId;
        $this->userId    = $userId;
        $this->source    = $source;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info("AutoCloseUsersStoriesLog start: ", ['storiesId' => $this->storiesId, 'userId' => $this->userId, 'source' => $this->source]);

        $info = FeishuCallingCardUsersStoriesLog::getInfo($this->storiesId, $this->userId);
        if (!$info) {
            $this->delete();
            return;
        }
        $time = time();

        // 生成延迟队列 延迟队列过期时间：3分钟 （3分钟之内同一个人同一篇文章阅读算一次）
        $autoScriptDelayTime = UsersStoriesLogService::getUsersStoriesConfig()['autoScriptDelayTime'] ?? 0;

        if ($time - $info->updatedAt->timestamp > $autoScriptDelayTime) {// 在超时时间内 未更新过记录
            self::autoClose($info->id, $info->duration, $info->isReadCompleted, $time, $info->createdAt->timestamp);
        } else {

            // 最多延迟3次
            if ($this->attempts() >= $this->tries) {
                self::autoClose($info->id, $info->duration, $info->isReadCompleted, $time, $info->createdAt->timestamp);

                $this->delete();
                return;
            }

            $this->release($autoScriptDelayTime + 1);// 延迟xx秒
        }
    }

    public static function autoClose(int $id, int $duration, int $isReadCompleted, int $time, int $createdAt)
    {
        $update = [
            'updatedAt' => $time,
            'type'      => FeishuCallingCardUsersStoriesLog::TYPE_AUTO_OFF,
            'exitTime'  => $createdAt + $duration,
        ];

        // 前端无法监控到篇幅，读完文章改成：阅读时间＞90S
        if (!$isReadCompleted && $duration) {
            $readCompleteTime = UsersStoriesLogService::getUsersStoriesConfig()['readCompleteTime'] ?? 0;
            if ($duration > $readCompleteTime) {
                $update['isReadCompleted'] = 1;
            }
        }
        $res = FeishuCallingCardUsersStoriesLog::query()
            ->where('id', $id)
            ->whereIn('type', [FeishuCallingCardUsersStoriesLog::TYPE_OPEN_ARTICLE, FeishuCallingCardUsersStoriesLog::TYPE_HEARTBEAT])
            ->update($update);

        Log::info('AutoCloseUsersStoriesLog autoClose: ', ['id' => $id, 'res' => $res, 'update' => $update]);

        // 发送飞书通知
        if ($res) {
            UsersStoriesLogService::sendFsNotice($id);
        }
    }
}
